package org.springside.examples.quickstart.util;

public class PasswordUtil {
	/**
	 * 解析盐值加密密码
	 * @param mergedPasswordSalt
	 * @return
	 */
    public static String[] demergePasswordAndSalt(String mergedPasswordSalt) {
        if ((mergedPasswordSalt == null) || "".equals(mergedPasswordSalt)) {
            throw new IllegalArgumentException("Cannot pass a null or empty String");
        }

        String password = mergedPasswordSalt;
        String salt = "";

        int saltBegins = mergedPasswordSalt.lastIndexOf("{");

        if ((saltBegins != -1) && ((saltBegins + 1) < mergedPasswordSalt.length())) {
            salt = mergedPasswordSalt.substring(saltBegins + 1, mergedPasswordSalt.length() - 1);
            password = mergedPasswordSalt.substring(0, saltBegins);
        }

        return new String[] {password, salt};
    }

    /**
     * 使用盐值密码
     * @param password
     * @param salt
     * @param strict
     * @return
     */
    public static String mergePasswordAndSalt(String password, Object salt, boolean strict) {
        if (password == null) {
            password = "";
        }

        if (strict && (salt != null)) {
            if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
                throw new IllegalArgumentException("Cannot use { or } in salt.toString()");
            }
        }

        if ((salt == null) || "".equals(salt)) {
            return password;
        } else {
            return password + "{" + salt.toString() + "}";
        }
    }
    /**
     * 使用盐值密码(盐值中不允许含有“{”和“}”)
     * @param password
     * @param salt
     * @return
     */
    public static String mergePasswordAndSalt(String password, Object salt) {
        return mergePasswordAndSalt(password, salt, true);
    }
}
